/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mobaas.devops.JsonResult;
import com.mobaas.devops.PageList;
import com.mobaas.devops.dao.AdminDao;
import com.mobaas.devops.model.Admin;
import com.mobaas.devops.service.AdminService;
import com.mobaas.devops.util.CryptoUtils;

/**
 * 
 * @author billy zhang
 * 
 */
@Service
public class AdminServiceImpl implements AdminService{
	
	@Autowired
	private AdminDao adminDao;

	@Override
	public JsonResult<Admin> selectAdminForLogin(String username, String passwd, String ip) {
		
		Admin admin = adminDao.selectAdminByName(username);
		if (admin == null) {
	    		return JsonResult.fail(-1, "用户不存在。");
	    }
		
		String encPasswd = CryptoUtils.MD5(CryptoUtils.MD5(passwd) + admin.getPwdSalt());
	    if (admin.getPassword().equalsIgnoreCase(encPasswd)) {
		    	admin.setLoginTime( new Date() );
		    	admin.setLoginIp( ip );
		    	adminDao.updateAdmin(admin);
	    		
			return JsonResult.ok(admin);
	    }
	    
	    return JsonResult.fail(-2, "密码错误。");
	    
	}

	@Override
	public Admin selectAdminById(int adminId) {
		return adminDao.selectAdminById(adminId);
	}

	@Override
	public PageList<Admin> selectAdminList(String keyword, int pageNum, int pageSize) {
		
		PageList<Admin> pi = new PageList<>();
		pi.setPageNo(pageNum);
		pi.setPageSize(pageSize);
		pi.setTotal( adminDao.selectAdminCount(keyword) );
		pi.setList( adminDao.selectAdminList(keyword, (pageNum-1) * pageSize, pageSize) );
		
		return pi;
	}

	@Override
	public void insertAdmin(Admin adm) {
		adminDao.insertAdmin(adm);
	}

	@Override
	public int updateAdmin(Admin adm) {
		return adminDao.updateAdmin(adm);
	}
	
	@Override
	public int deleteAdmin(int admId) {
		return adminDao.deleteAdmin(admId);
	}
	
	@Override
	public int selectAdminCountByName(String name) {
		return adminDao.selectAdminCountByName(name);
	}
	
}
